package org.finesys.common.redis.core.event.listener.impl;

import java.util.ArrayList;
import java.util.List;

import org.finesys.common.redis.core.event.consume.KeyExpiredEventMessageConsume;
import org.finesys.common.redis.core.event.listener.AbstractKeyExpiredEventMessageListener;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.util.ObjectUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * key过期事件监听
 */
@Slf4j
public class DefaultKeyExpiredEventMessageListener extends AbstractKeyExpiredEventMessageListener {

	private List<KeyExpiredEventMessageConsume> keyExpiredEventMessageConsumeList;

	@Override
	public void onMessage(Message message, byte[] pattern) {

		if (ObjectUtils.isEmpty(keyExpiredEventMessageConsumeList)) {
			return;
		}
		super.onMessage(message, pattern);

		String key = message.toString();
		for (KeyExpiredEventMessageConsume keyExpiredEventMessageConsume : keyExpiredEventMessageConsumeList) {
			if (keyExpiredEventMessageConsume.support(key)) {
				if (log.isDebugEnabled()) {
					log.debug("{} handle key expired event,the expired key is {}",
							keyExpiredEventMessageConsume.getClass().getName(), key);
				}
				keyExpiredEventMessageConsume.consume(key);
			}
		}
	}

	public DefaultKeyExpiredEventMessageListener(RedisMessageListenerContainer listenerContainer,
			ObjectProvider<List<KeyExpiredEventMessageConsume>> objectProvider) {
		super(listenerContainer);
		objectProvider.ifAvailable(consumer -> {
			this.keyExpiredEventMessageConsumeList = new ArrayList<>(consumer);
		});
	}

}
